const express = require("express");
const mongoose = require("mongoose");

const app = express();

const schema = new mongoose.Schema({
  filmId: Number,
  name: String,
});

const Model = mongoose.model("Film", schema);

// 注册路由
app.get("/films", async (req, res) => {
  try {
    // 取入参
    const { page = 1, pageSize = 10 } = req.query;

    const docs = await Model.find({}, "filmId name", {
      skip: (page - 1) * pageSize,
      limit: pageSize,
    });
    // 获取总条数
    const total = await Model.count();

    res.send({
      code: 0,
      msg: "ok",
      data: {
        pageTotal: Math.ceil(total / pageSize), // 总页数
        total: total, // 总条数
        list: docs,
      },
    });
  } catch (error) {
    res.send({
      code: -1,
      msg: error.message || error,
      data: null,
    });
  }
});

async function main() {
  await mongoose.connect("mongodb://127.0.0.1:27017/maizuo");

  app.listen(3000, () => {
    console.log("服务启动成功");
  });
}

main();
